<template>
  <div class="theme-education">
    <!-- 顶部选项卡和创建按钮 -->
    <div class="education-header">
      <!-- 锚点导航 -->
      <div class="anchor-nav">
        <el-scrollbar>
          <div class="nav-items">
            <div
                v-for="theme in themes"
                :key="theme.name"
                class="nav-item"
                :class="{ active: activeTheme === theme.name }"
                @click="scrollToTheme(theme.name)"
            >
              {{ theme.label }}
            </div>
          </div>
        </el-scrollbar>
      </div>

      <el-button type="primary" class="create-btn" @click="showCreateDialog">
        <el-icon>
          <Plus/>
        </el-icon>
        创建主题学习
      </el-button>
    </div>

    <ThemeCreateDialog
        v-model="createDialogVisible"
        :theme-options="themes"
        @submit="handleCreateSubmit"
        @cancel="handleCreateCancel"
    />

    <!-- 主题内容区域 -->
    <div class="theme-content">
      <div
          v-for="theme in themes"
          :key="theme.name"
          :id="'theme-' + theme.name"
          class="theme-section"
      >
        <h2 class="theme-title">{{ theme.label }}</h2>
        <div class="theme-layout">
          <div class="left-large">
            <img
                :src="theme.coverImage"
                :alt="theme.label"
                @error="handleImageError"
            >
          </div>
          <div class="right-items">
            <div v-for="item in theme.subThemes" :key="item.id" class="content-item">
              <img
                  :src="item.coverImage"
                  :alt="item.label"
                  @error="handleImageError"
              >
              <div class="item-content">
                <h4>{{ item.label }}</h4>
                <p>{{ item.description }}</p>
              </div>
            </div>
          </div>
        </div>

        <!-- 在每个主题section底部添加查看更多 -->
        <div class="theme-more">
          <router-link
              :to="`courses/theme-detail/${theme.id}`"
              class="more-link"
          >
            查看更多内容
            <el-icon><ArrowRight /></el-icon>
          </router-link>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import {onMounted, ref, onUnmounted} from 'vue';
import {Plus} from '@element-plus/icons-vue';
import ThemeCreateDialog from './ThemeCreateDialog.vue';
import {fetchThemes} from "@/api/teacher";
import { ElMessage } from 'element-plus'

const themes = ref([]);
const activeTheme = ref('');
const createDialogVisible = ref(false);

// 滚动到指定主题
const scrollToTheme = (themeName) => {
  const element = document.getElementById(`theme-${themeName}`);
  if (element) {
    activeTheme.value = themeName;
    element.scrollIntoView({
      behavior: 'smooth',
      block: 'start'
    });
  }
};

// 监听滚动，更新激活的主题
const handleScroll = () => {
  const sections = document.querySelectorAll('.theme-section');
  const scrollPosition = window.scrollY + 100; // 加上一些偏移量

  sections.forEach(section => {
    const sectionTop = section.offsetTop;
    const sectionHeight = section.offsetHeight;
    const sectionId = section.id.replace('theme-', '');

    if (scrollPosition >= sectionTop && scrollPosition < sectionTop + sectionHeight) {
      activeTheme.value = sectionId;
    }
  });
};

// 图片错误处理
const handleImageError = (event) => {
  const img = event.target;
  img.src = 'data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100" viewBox="0 0 100 100"><rect width="100" height="100" fill="%23f5f5f5"/><text x="50" y="50" font-family="Arial" font-size="12" fill="%23999" text-anchor="middle" dominant-baseline="middle">图片加载失败</text></svg>';
  event.stopPropagation();
};

const loadData = async () => {
  try {
    const res = await fetchThemes()
    if (res.success) {
      themes.value = res.data
      if (themes.value.length > 0) {
        activeTheme.value = themes.value[0].name
      }
    } else {
      ElMessage.warning(res.message || '获取主题数据失败')
    }
  } catch (error) {
    if (error.response?.status === 404) {
      ElMessage.error('主题数据接口不存在')
    } else if (error.response?.status === 500) {
      ElMessage.error('服务器内部错误，请稍后重试')
    } else if (error.code === 'NETWORK_ERROR') {
      ElMessage.error('网络连接失败，请检查网络设置')
    } else {
      ElMessage.error('主题加载失败，请稍后重试')
    }
  }
};

onMounted(() => {
  loadData()
  window.addEventListener('scroll', handleScroll)
})

onUnmounted(() => {
  window.removeEventListener('scroll', handleScroll)
})

const showCreateDialog = () => {
  createDialogVisible.value = true;
};

const handleCreateSubmit = (formData) => {
  loadData()
  console.log('创建主题:', formData);
};

const handleCreateCancel = () => {
  console.log('用户取消了创建');
};
// 添加查看更多处理方法
const handleViewMore = (theme) => {
  ElMessage.info(`查看${theme.label}的更多内容（功能开发中）`)
  console.log('查看更多:', theme.name)
  // 这里可以添加跳转到详情页的逻辑
  // router.push(`/themes/${theme.name}`)
}
</script>

<style scoped>
/* 新增锚点导航样式 */
.anchor-nav {
  flex: 1;
  margin-right: 20px;
}

.nav-items {
  display: flex;
  gap: 20px;
  padding: 8px 0;
}

.nav-item {
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  color: #606266;
  transition: all 0.3s ease;
  white-space: nowrap;
}

.nav-item:hover {
  background-color: #f5f7fa;
  color: #409eff;
}

.nav-item.active {
  background-color: #ecf5ff;
  color: #409eff;
  font-weight: 600;
}

/* 为每个主题区域添加滚动边距 */
.theme-section {
  margin-bottom: 40px;
  scroll-margin-top: 80px; /* 确保滚动时标题不被导航栏遮挡 */
}

/* 保持您原有的所有其他样式不变 */
.theme-education {
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
}

.education-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.create-btn {
  margin-left: 20px;
}

.theme-content {
  min-height: 500px;
}

.theme-title {
  font-size: 22px;
  color: #303133;
  margin-bottom: 10px;
}

.theme-description {
  font-size: 16px;
  color: #606266;
  margin-bottom: 20px;
}

.theme-layout {
  display: flex;
  gap: 20px;
}

.left-large {
  flex: 0 0 60%;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.left-large img {
  width: 100%;
  height: 300px;
  object-fit: cover;
}

.right-items {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.content-item {
  display: flex;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  height: 100px;
}

.content-item img {
  width: 120px;
  height: 100%;
  object-fit: cover;
}

.item-content {
  padding: 10px 15px;
  flex: 1;
}

.item-content h4 {
  margin: 0 0 8px 0;
  font-size: 16px;
  color: #303133;
}

.item-content p {
  margin: 0;
  font-size: 14px;
  color: #606266;
}

.theme-more {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
  text-align: center;
}

.more-link {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  color: #409eff;
  text-decoration: none;
  font-size: 14px;
  font-weight: 500;
  padding: 8px 16px;
  border: 1px solid #409eff;
  border-radius: 4px;
  transition: all 0.3s ease;
}

.more-link:hover {
  background-color: #409eff;
  color: white;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
}

.more-link .el-icon {
  font-size: 12px;
  transition: transform 0.3s ease;
}

.more-link:hover .el-icon {
  transform: translateX(2px);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .theme-more {
    margin-top: 15px;
    padding-top: 15px;
  }

  .more-link {
    padding: 6px 12px;
    font-size: 13px;
  }
}
</style>
